import datetime
from typing import List, Dict

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, ForeignKey, text, and_
from sqlalchemy.orm import Session, relationship

from common.database import Base
from common.database import SessionMixin


class MonitorLogService(Base, SessionMixin):
    __tablename__ = 'monitor_log_service'
    service_name = Column(String(128), nullable=False, comment="服务名称")
    log_collect_status = Column(Boolean, default=text('true'), nullable=False, comment="日志收集状态")
    type = Column(String(30), nullable=False, comment="类型")  # 应用服务 application|数据库 database|大数据 bigdata
    # service2policy = relationship('MonitorLogPolicy', uselist=False, backref='policy2service')  # 只需要在一对多关系基础上的父表中使用 uselist 参数来表示
    # service2character = relationship('MonitorLogCharacter', backref='character2service')
    # service2keyword = relationship('MonitorLogCharacter', backref='keyword2service')
    create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")
    update_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, nullable=False,
                         comment="更新时间")

    __table_args__ = (
        Index('idx_monitor_log_service_uuid', 'uuid', unique=True),
        Index('idx_monitor_log_service_service_name', 'service_name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return "<uuid='{}',service_name='{}'>".format(self.uuid, self.service_name)

    @classmethod
    def get_policy_by_service_name(cls, db: Session, service_name: str) -> Dict:
        service = db.query(cls).filter(cls.service_name == service_name).first()
        return cls.to_dict(service.policy2service) if service else {}

        # for item in services.service2exclude_keyword:
        #
        # return cls.to_dict(services.service2exclude_keyword) if services else {}

    @classmethod
    def create_service(cls, db: Session, service_name: str, log_collect_status: int, department: str, type: str, alarm_threshold: int,
                       alarm_plan: Dict, is_maintain: int, maintain_begin_time: str, maintain_end_time: str, notice_group: list,
                       username: str, exclude_keyword: list, is_active, effective_datetime, expiration_datetime):
        monitor_log_service = MonitorLogService.add(db, service_name, log_collect_status, department, type)

    # @classmethod
    # def get_service_by_name(cls, db: Session, service_name):


# monitor_log_policy = monitor_log_service.service2policy(service_name, alarm_plan, alarm_threshold, is_maintain, maintain_begin_time,
#                                                         maintain_end_time, notice_group)
# monitor_log_policy.c.service2exclude_keyword(username, exclude_keyword, is_active, effective_datetime, expiration_datetime)


if __name__ == "__main__":
    from common.database import SessionLocal

    session = SessionLocal()
    current_datetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    MonitorLogService.get_exclude_keyword_by_service_name(session, "message-sms", current_datetime)
    # session = SessionLocal()
    # MonitorLogService.add(session, {"service_name": "user-center", "log_collect_status": True, "department": "运维", "type": "应用服务"})
    # MonitorLogService.create_service(session, service_name="user-center", log_collect_status=True, department="运维", type="应用服务",
    #                                  alarm_threshold=50, alarm_plan={"a": "1"}, is_maintain=1, maintain_begin_time="2023-03-27 17:00:00",
    #                                  maintain_end_time="2023-03-27 18:00:00", notice_group=["运维组"], username="boll.lai",
    #                                  exclude_keyword=["ERROR"], is_active=1, effective_datetime="2023-03-27 17:00:00",
    #                                  expiration_datetime="2023-03-27 18:00:00")
    # print(kudu_table_info.get_latest_time_range(session))

    # sch_obj = School(name='TreasureShanghai')
    # sch_obj.sch2stu = [Student(name='徐建-上海'),
    #                    Student(name='徐建2-上海')]
    # db_session.add(sch_obj)
    #
    # @classmethod
    # def get_entries(cls, db: Session) -> List[Dict]:
    #     return db.query(cls).outerjoin(
    #         MonitorLogPolicy, cls.monitor_log_policy_uuid == MonitorLogPolicy.uuid).with_entities(
    #         cls.uuid.label('uuid'), cls.service_name.label('service_name'), cls.app_log_status.label('log_collect_status'),
    #         # MonitorLogPolicy.exclude_keywords.label('exclude_keywords'),
    #         MonitorLogPolicy.alarm_threshold.label('alarm_threshold'),
    #         MonitorLogPolicy.is_maintain.label('is_maintain'),
    #         MonitorLogPolicy.alarm_plan.label('alarm_plan'),
    #         MonitorLogPolicy.maintain_begin_time.label('maintain_begin_time'),
    #         MonitorLogPolicy.maintain_end_time.label('maintain_end_time'),
    #         MonitorLogPolicy.notice_users.label('notice_users'),
    #         MonitorLogPolicy.create_time.label('create_time'),
    #         MonitorLogPolicy.update_time.label('update_time')).to_dict()
    #
    # @classmethod
    # def get_policy_paginate(cls, db: Session, page, per_page) -> List[Dict]:
    #     return db.query(cls).outerjoin(
    #         MonitorLogPolicy, cls.monitor_log_policy_uuid == MonitorLogPolicy.uuid).with_entities(
    #         cls.uuid.label('uuid'), cls.service_name.label('service_name'), cls.app_log_status.label('log_collect_status'),
    #         # MonitorLogPolicy.exclude_keywords.label('exclude_keywords'),
    #         MonitorLogPolicy.alarm_threshold.label('alarm_threshold'),
    #         MonitorLogPolicy.is_maintain.label('is_maintain'),
    #         MonitorLogPolicy.alarm_plan.label('alarm_plan'),
    #         MonitorLogPolicy.maintain_begin_time.label('maintain_begin_time'),
    #         MonitorLogPolicy.maintain_end_time.label('maintain_end_time'),
    #         MonitorLogPolicy.notice_users.label('notice_users'),
    #         MonitorLogPolicy.create_time.label('create_time'),
    #         MonitorLogPolicy.update_time.label('update_time')).paginate(page, per_page)

    # cmdbAliyunDomainSubquery = db.session.query(cmdbAliyunDomainRecord).with_entities(
    #     cmdbAliyunDomainRecord.account, cmdbAliyunDomainRecord.domain_name, cmdbAliyunDomainRecord.rr,
    #     cmdbAliyunDomainRecord.value, cmdbAliyunDomainRecord.type, cmdbAliyunDomainRecord.record_id,
    #     cmdbAliyunDomainRecord.ttl, cmdbAliyunDomainRecord.line, cmdbAliyunDomainRecord.locked,
    #     cmdbAliyunDomainRecord.status,
    #     func.date_format(cmdbAliyunDomainRecord.ctime, "%Y-%m-%d").label('ctime')).filter(
    #     cmdbAliyunDomainRecord.ctime == date).subquery()
    #
    # data = db.session.query(cmdbAliyunDomainSubquery).outerjoin(cmdbAliyunDomain, and_(
    #     cmdbAliyunDomainSubquery.c.account == cmdbAliyunDomain.account,
    #     cmdbAliyunDomainSubquery.c.domain_name == cmdbAliyunDomain.domain_name,
    #     cmdbAliyunDomainSubquery.c.ctime == cmdbAliyunDomain.ctime)).with_entities(
    #     cmdbAliyunDomainSubquery.c.account.label('account'),
    #     func.concat_ws('.', cmdbAliyunDomainSubquery.c.rr, cmdbAliyunDomainSubquery.c.domain_name).label(
    #         'domain_name'),
    #     cmdbAliyunDomainSubquery.c.value.label('value'),
    #     cmdbAliyunDomainSubquery.c.type.label('type'),
    #     cmdbAliyunDomainSubquery.c.record_id.label('record_id'),
    #     cmdbAliyunDomainSubquery.c.ttl.label('ttl'),
    #     cmdbAliyunDomainSubquery.c.line.label('line'),
    #     cmdbAliyunDomainSubquery.c.locked.label('locked'),
    #     cmdbAliyunDomainSubquery.c.status.label('status'),
    #     cmdbAliyunDomain.instance_id.label('instance_id'),
    #     cmdbAliyunDomain.domain_name.label('domain'),
    #     cmdbAliyunDomain.registration_date.label('registration_date'),
    #     cmdbAliyunDomain.domain_audit_status.label('domain_audit_status'),
    #     cmdbAliyunDomain.domain_type.label('domain_type'),
    #     cmdbAliyunDomain.domain_status.label('domain_status'),
    #     cmdbAliyunDomain.expiration_date.label('expiration_date'),
    #     cmdbAliyunDomain.ctime.label('ctime')).to_dict()
